package com.stoneapple.timesheet.ProfileServlet;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.stoneapple.timesheet.Constrain;
import com.stoneapple.timesheet.dao.ProfileDao;

@SuppressWarnings("serial")
public class CreateProfileServlet extends HttpServlet {

	private static final Logger log = Logger
			.getLogger(CreateProfileServlet.class.getName());

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		if (user == null) {
			String loginUrl = userService.createLoginURL(req.getRequestURI());
			resp.sendRedirect(loginUrl);

		} else {
			log.info("User Id: " + user);

			String firstname = Constrain.checkNullString(req
					.getParameter("firstname"));
			String lastname = Constrain.checkNullString(req
					.getParameter("lastname"));
			String nickname = Constrain.checkNullString(req
					.getParameter("nickname"));
			String position = Constrain.checkNullString(req
					.getParameter("position"));
			String employeecode = Constrain.checkNullString(req
					.getParameter("employeecode"));
			String country = Constrain.checkNullString(req
					.getParameter("country"));

			log.info("Profile information:");
			log.info("First Name: " + firstname + ", Last Name: " + lastname
					+ ",Nick Name: " + nickname + ",Position: " + position
					+ ",Employee Code: " + employeecode + ",Country: "
					+ country);

			ProfileDao profiledao = ProfileDao.getInstance();
			profiledao.save(user.getUserId(), firstname, lastname, nickname,
					position, employeecode, country);

			resp.sendRedirect("/profile");
		}
	}
}
